package com.shuorikeji.huohuo.http;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.google.gson.JsonParseException;
import com.shuorikeji.huohuo.R;
import com.shuorikeji.huohuo.app.AppManager;
import com.shuorikeji.huohuo.app.MyApplication;
import com.shuorikeji.huohuo.base.RxBasePresenter;
import com.shuorikeji.huohuo.common.NetConfig;
import com.shuorikeji.huohuo.ui.LoginActivity;
import com.shuorikeji.huohuo.utils.ToastShowUtil;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.ParseException;

import androidx.fragment.app.Fragment;
import retrofit2.HttpException;
import rx.Subscriber;


/**
 * 封装的Subscriber供网络请求实现订阅
 * Created by wxl
 */

public abstract class HttpSubscriber<T> extends Subscriber<Object> {
    private String intentFlag = "";
    private Context mContext;
    private int noShowToast = 0;     //不显示Toast
    private Dialog loadingDialog;

    /**
     * 需要加载的dialog时调用
     */
    @SuppressWarnings("unused")
    public HttpSubscriber(RxBasePresenter presenter, boolean show) {
        super();
        if (show) {
            loadingDialog = presenter.loadingDialog;
        }
        if (presenter.mView instanceof Fragment) {
            mContext = ((Fragment) (presenter.mView)).getActivity();
        } else if (presenter.mView instanceof Activity) {
            mContext = (Context) presenter.mView;
        }
        if (show) {
            if (loadingDialog != null) {
                loadingDialog.show();
            }
        }
    }


    /**
     * 网络访问后台成功，后台返回的数据封装httpResult
     */
    @Override
    public void onNext(Object httpResult) {
    }

    /**
     * 网络访问后台异常
     */
    @Override
    public void onError(Throwable e) {
        if (noShowToast == 0) {
            dealException(MyApplication.getInstance(), e);
        }
        if (loadingDialog != null) {
            loadingDialog.dismiss();
            loadingDialog = null;
        }
    }

    /**
     * 处理异常错误
     *
     * @param t
     */
    void dealException(Context context, Throwable t) {
        if (t instanceof ConnectException || t instanceof UnknownHostException) {
            //连接错误
            onException(NetConfig.CONNECT_ERROR, context);
        } else if (t instanceof InterruptedException) {
            //连接超时
            onException(NetConfig.CONNECT_TIMEOUT, context);
        } else if (t instanceof JsonParseException
                || t instanceof JSONException
                || t instanceof ParseException) {
            //解析错误
            onException(NetConfig.PARSE_ERROR, context);
        } else if (t instanceof SocketTimeoutException) {
            //请求超时
            onException(NetConfig.REQUEST_TIMEOUT, context);
        } else if (t instanceof UnknownError) {
            //未知错误
            onException(NetConfig.UNKNOWN_ERROR, context);
        } else if (t instanceof HttpException) {
            //未登录
            try {
                if (t.getMessage().contains("HTTP 501")) {
                    //需要看广告解锁
                    ToastShowUtil.showToastCenter(mContext, "请到福利-任务广场观看观看解锁新内容");
                } else {
                    ToastShowUtil.showToastCenter(mContext, "登录过期，请重新登录");
                    AppManager.getAppManager().finishAllActivity();
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    mContext.startActivity(intent);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            //未知错误
            onException(NetConfig.UNKNOWN_ERROR, context);
        }
    }


    void onException(int errorCode, Context context) {
        switch (errorCode) {
            case NetConfig.CONNECT_ERROR:
                ToastShowUtil.showToastCenter(context, "ip access failure");
                break;
            case NetConfig.CONNECT_TIMEOUT:
                ToastShowUtil.showToastCenter(context, context.getResources().getString(R.string.connect_timeout));
                break;
            case NetConfig.PARSE_ERROR:
                ToastShowUtil.showToastCenter(context, context.getResources().getString(R.string.parse_error));
                break;
            case NetConfig.REQUEST_TIMEOUT:
                ToastShowUtil.showToastCenter(context, "Request access timeout");
                break;
            case NetConfig.UNKNOWN_ERROR:
                ToastShowUtil.showToastCenter(context, "Unknown error");
                break;
            default:
                ToastShowUtil.showToastCenter(context, "The network request failed. Please try again later");
                break;
        }
    }

    /**
     * 网络访问结束
     */
    @Override
    public void onCompleted() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        Log.i("网络访问结束", "onCompleted");
    }
}
